import SessionUtil from '../../data/session/session'
import AppSceneUtil from '../../data/common/appScene'
import create from '../../utils/create2.js'
import store from '../../store/index.js'
import PagePromoterUtil, { PagePromoter } from '../../data/common/pagePromoter';
create(store, {
  /**
   * 页面的初始数据
   */
  data: {
    year: '',
    active: -1,
    pageSize: 10,
    pageNo: 0,
    load: false,
    tips: '加载更多',
    type: 'lower',
    keyWords: '',
    windowHeight: 0,
    list: [],
    hideCart: true,
    chosenItem: {},
    quantity: 1,
    stock: 0,
    cartLength: 0,
    show_year:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getApp().getSaleMode()
    PagePromoterUtil.showShareMenu().then()
    SessionUtil.getInstance().then(()=>{
      AppSceneUtil.setPageScene(this)
    })
    const { year } = options
    this.setData({ year })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    SessionUtil.getInstance().then(()=>{
      this.scroller = this.selectComponent('#scroller')
      this.shoppingBar = this.selectComponent('#shopping')
      const { cartLength} = this.data
      if (cartLength > 0) this.scroller.minusHeight(50)
      this.queryData()
    })
  },
  onHide(){
    const { cartLength } = this.data
    if (cartLength > 0) this.scroller.minusHeight(-50)
  },
  tabClick(e) {
    const { dataset } = e.currentTarget
    const { index } = dataset
    let year = new Date().getFullYear()

    this.setData({
      active: index,
      type: 'upper',
      pageNo: 1,
      keyWords: '',
      year: index * 1 === 0 ? `${year} - ${year - 3}` : `${year} - ${year - 5}`
    })
    this.queryData()
  },
  queryData() {
    let { pageSize, pageNo, keyWords, type, list, year } = this.data
    if (pageNo < 0) {
      this.setData({
        load: false,
        tips: '没有更多了'
      })
      return
    }
    if (type === 'upper') {
      this.scroller.showLoading()
    } else {
      pageNo += 1
    }
    wx.$http().request({
      url: '/AppMaster/item/itemList', data: {
        pageSize, pageNo, name: keyWords,
        yearId: year
      }, method: 'GET'
    }).then(_ => {
      const { _data } = _
      const { data } = _data
      const { count } = data
      this.scroller.hideLoading()
      this.setData({
        list: pageNo > 1 ? list.concat(data.list) : data.list,
        load: false,
        tips: data.list.length < 10 ? '没有更多了' : '加载更多',
        pageNo: data.list.length < 10 ? -1 : pageNo
      });
    }).catch(err=>{
      console.log(err)
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  searchHandler(e) {
    const { detail } = e
    this.setData({
      keyWords: detail,
      pageNo: 1,
      type: 'upper'
    })
    this.queryData()
  },
  lower() {
    let { pageNo } = this.data
    this.setData({
      type: 'lower'
    })
    this.queryData()
  },
  upper() {
    this.setData({
      pageNo: 1,
      type: 'upper'
    })
    this.queryData()
  },
  AddCart: function (e) {
    let ID = e.currentTarget.id
    const itemId = ID.split('-')[0];
    const stock = ID.split('-')[1];
    let chosenItem;
    if (stock < 1) {
      wx.showToast({
        title: '库存不足！',
        image: '../../pages/images/fail.png',
        duration: 2000
      })
      return false;
    }
    // 显示年份
    wx.$http().request({
      url: '/AppMaster/Item/getItemYearsList',
      method: 'GET',
      data: {
        item_id: itemId
      },
      success: (res) => {
        const { data } = res
        const { result } = data
        if (result == 0) {
          const normalInfo = data.data.item_info;
          const list_year = data.data.item_year_list;
          let activity = normalInfo.activity_category;
          if (activity != 0) {
            activity = activity.split(",");
          }
          this.setData({
            chosenItem: normalInfo,
            list_year: list_year,
            activity: activity,
            hideCart: false,
            stock,
            itemId
          })
        }
      }
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  addNum() {
    let { quantity, stock } = this.data
    if (quantity + 1 <= stock) {
      this.setData({
        quantity: quantity + 1,
        stock: stock - 1
      })
    } else {
      this.setData({
        quantity,
        stock: 0
      })
    }
  },
  minusNum() {
    let { quantity, stock } = this.data
    if (quantity - 1 > 0) {
      this.setData({
        quantity: quantity - 1,
        stock: stock + 1
      })
    } else if (quantity - 1 === 0) {
      this.setData({
        quantity: 1,
        stock: stock + 1
      })
    } else {
      this.setData({
        quantity: 1,
        stock
      })
    }
  },
  addCartHandler() {
    const { quantity, itemId } = this.data
    wx.$http().request({
      url: '/AppMaster/PosCart/PosAddCart',
      method: 'POST',
      data: {
        number: quantity,
        itemId
      }
    }).then(jxbResp=>{
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          quantity: 1,
          hideCart:true
        }),
        this.shoppingBar.queryCart()
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  minusHeight (){
    if (this.scroller){
      this.scroller.minusHeight(50)
    }
    this.setData({
      cartLength : 1
    })
  },

  onShareAppMessage: function(){
    let session = SessionUtil.getInstanceSync(),
    resp = (new PagePromoter( this.route, this.options))
      .setShareTitle(session.getTheSellingServerSync().showName)
      .buildShareInfo()
    console.log(resp, '分享内容')
    return resp
  },
  goDetail(e) {
    const itemId = e.currentTarget.id;
    this.setData({
      Details: false,
    })
    wx.navigateTo({
      url: '/pages/product/detail/detail?itemId=' + itemId
    })
  }
})